
package com.probiz.estoresa.attribute.web.action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;

import com.probiz.estore.attribute.service.AttributeManager;
import com.probiz.estore.common.model.attribute.Attribute;
import com.probiz.estore.core.controller.GenericStoreAdminController;
import com.probiz.estore.core.exception.ApplicationException;
import com.probiz.estore.webapp.util.RequestUtil;

public class AttributeDefinerController extends GenericStoreAdminController<Attribute> {
	private AttributeManager	attributeManager	= null;
    
	public void setAttributeManager(AttributeManager inMgr) {
		this.attributeManager = inMgr;
	}

	protected String getEntityName(Attribute entity) {
		
		return entity.getAttributeName();
	}

	protected void initController() throws Exception {
		this.mgr = attributeManager;
	}

	protected void preSave(HttpServletRequest request, Attribute entity,
			BindException errors) {
	}

	public ModelAndView defaultAction(HttpServletRequest request,
			HttpServletResponse response) {
		ModelAndView mv = new ModelAndView("attribute/attributeDefiner");
		Integer module = RequestUtil.getInteger(request, "module");
		Attribute attribute = formBackingObject(request);
		if(null!=module)attribute.setAttributeType(module.shortValue());
		mv.addObject("attribute", attribute);
		return mv;
	}
	
	public ModelAndView save(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Attribute attribute = formBackingObject(request);
		BindException errors = null;
		JSONObject attributeJSON = null;
		try {
			ServletRequestDataBinder binder = bindAndValidate(request, attribute);
			errors = new BindException(binder.getBindingResult());
			if (!errors.hasErrors()) {
				
				attributeManager.saveFully(attribute);
				attributeJSON = attributeManager.getJSONObject(attribute);
			}
		} catch (ApplicationException e) {
			handleApplicationException(errors, e);
		}
		try {
			PrintWriter out = response.getWriter();
			out.println(attributeJSON.toString()); 
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 刷新缺省值区域
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView refreshDefaultValue(HttpServletRequest request,	HttpServletResponse response) {
		ModelAndView mv = new ModelAndView("attribute/include/attributeDefinerDefaultValue");
		Attribute attribute = new Attribute();
		attribute.setAttributeDataType(RequestUtil.getInteger(request, "dataType"));
		mv.addObject("attribute", attribute);
		return mv;
	}

}
